//
//  MapController.m
//  BonBon
//
//  Created by Infindo Eric on 09-12-25.
//  Copyright 2009 苏州. All rights reserved.
//

#import "MapController.h"
#import "MapAnnotation.h"


@implementation MapController
@synthesize mapView;
@synthesize mapListArray;
@synthesize userCurrentLocation,locationManager;

- (void)viewDidLoad {
	UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 416.0f)];
	self.view = view;
	[view release];
	
	//lianshen
	self.locationManager = [[CLLocationManager alloc] init];
	self.locationManager.delegate = self;
	self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
	[self.locationManager startUpdatingLocation];
	
	//end
	mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 416.0f)];
	mapView.delegate = self;
	mapView.showsUserLocation = YES;
	[self.view addSubview:mapView];
	
	mapListArray = [[NSMutableArray alloc] init];
	destination = [[NSString alloc] init];
	
    [super viewDidLoad];
}
- (void)dealloc {
	for (UIView *view in [self.view subviews]) {
		[view removeFromSuperview];
	}
	[mapView release];
	
	[locationManager release];	
	[userCurrentLocation release];
	
	[mapListArray release];
	[destination release];
    [super dealloc];
}
- (void)setMapByLatitude:(float)lat longitude:(float)lng shopName:(NSString *)name {
	//create dic and store inside an array , so that we can add it into mapListArray
	NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
	[tempDict setObject:[NSString stringWithFormat:@"%f",lat] forKey:@"GMapLat"];
	[tempDict setObject:[NSString stringWithFormat:@"%f",lng] forKey:@"GMapLng"];
	[tempDict setObject:name forKey:@"Name"];
	NSMutableArray* tempArray = [[NSMutableArray alloc]init];
	[tempArray addObject:tempDict];
	
	[mapListArray setArray:tempArray];
	[tempArray release];
	[tempDict release];
	//end
	
	CLLocationCoordinate2D theCoordinate;
	theCoordinate.latitude =lat;
	theCoordinate.longitude=lng;
	MKCoordinateRegion theRegin;
	MapAnnotation * ano = [[MapAnnotation alloc] initWithCoords:theCoordinate name:name];
	
	[mapView addAnnotation:ano ];
	[ano release];
	CLLocationCoordinate2D theCenter;
	theCenter.latitude =lat; 
	theCenter.longitude = lng;
	theRegin.center=theCenter;
	MKCoordinateSpan theSpan;
	theSpan.latitudeDelta = 0.1;
	theSpan.longitudeDelta = 0.1;
	theRegin.span = theSpan;
	[mapView setRegion:theRegin];
	[mapView regionThatFits:theRegin];
	mapView.showsUserLocation = YES;
}
- (void)setMapByList:(NSArray *)array {
	float totalLat = 0.0f,totalLng = 0.0f;
	[mapListArray setArray:array];
	for (int i = 0; i < [array count]; i ++) {
		NSDictionary *dict = (NSDictionary *)[array objectAtIndex:i];
		float tempLat = [[dict objectForKey:@"GMapLat"] floatValue];
		float tempLng = [[dict objectForKey:@"GMapLng"] floatValue];
		///NSString *tempName = [dict objectForKey:@"Name"];
		NSString *tempName = [NSString stringWithFormat:@"%@\n%@, %@, %@\n%@",[dict objectForKey:@"StreetName"],
									  [dict objectForKey:@"DistrictName"],[dict objectForKey:@"CityName"],[dict objectForKey:@"CountryName"],
									  [[dict objectForKey:@"HotspotName"] length]?[dict objectForKey:@"HotspotName"]:@""];
	
		CLLocationCoordinate2D theCoordinate;
		theCoordinate.latitude =tempLat;
		theCoordinate.longitude=tempLng;
		MapAnnotation * ano = [[MapAnnotation alloc] initWithCoords:theCoordinate name:tempName];
		[mapView addAnnotation:ano ];
		[ano release];
		totalLat += tempLat;
		totalLng += tempLng;
	}
	MKCoordinateRegion theRegin;
	CLLocationCoordinate2D theCenter;
	theCenter.latitude =totalLat/[array count]; 
	theCenter.longitude = totalLng/[array count];
	
	theRegin.center=theCenter;
	MKCoordinateSpan theSpan;
	theSpan.latitudeDelta = 0.1;
	theSpan.longitudeDelta = 0.1;
	theRegin.span = theSpan;
	[mapView setRegion:theRegin];
	[mapView regionThatFits:theRegin];
	mapView.showsUserLocation = YES;
}
#pragma mark MapView delegate

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
	
	if ([annotation isKindOfClass:[MapAnnotation class]]) {
		
		MapAnnotation *mapAnno = (MapAnnotation *)annotation;
		static NSString *AnoViewIdentifier = @"voucherMapAnoView";
		MKAnnotationView *anoView = [[MKAnnotationView alloc] initWithAnnotation:mapAnno
																 reuseIdentifier:AnoViewIdentifier];
		anoView.image = [UIImage imageNamed:@"mapPin.png"];
		//anoView.image = nil;
		anoView.canShowCallout = YES;
		UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
		button.tag = mapAnno.tag;
		[button addTarget:self action:@selector(mapPinDetailPressed:) forControlEvents:UIControlEventTouchUpInside];
		anoView.rightCalloutAccessoryView = button;
		return anoView;
	}
	return nil;
}

- (void)mapPinDetailPressed:(id)sender {
	UIButton *button = (UIButton *)sender;
	NSDictionary *dict = (NSDictionary *)[mapListArray objectAtIndex:button.tag];
	tempLatitude = [[dict objectForKey:@"GMapLat"] floatValue];
	tempLongitude = [[dict objectForKey:@"GMapLng"] floatValue];
	destination=[dict objectForKey:@"Name"];
	[self showGoogleMap];
}

-(void) showGoogleMap
{
	UIAlertView *alert = [[UIAlertView alloc]
						  initWithTitle:@"导航" message:[NSString stringWithFormat: @"转到地图程序，导航到该公司?"]//,appName]
						  delegate:self cancelButtonTitle:nil otherButtonTitles:@"是的",@"取消",nil];
	
	[alert show];
	[alert release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if(buttonIndex==0)
	{
		NSString* startLocation = [[NSString alloc] initWithString:@"当前位置"];
		NSString* finalLocation = destination;
		//NSString *urlString =[NSString stringWithFormat:@"http://maps.google.com/maps?daddr=%@@2.759591,101.732368&saddr=%@@%f,%f",[finalLocation stringByReplacingOccurrencesOfString:@" " withString:@"+"],[startLocation stringByReplacingOccurrencesOfString:@" " withString:@"+"],mapView.userLocation.coordinate.latitude,mapView.userLocation.coordinate.longitude];
		NSString *urlString =[NSString stringWithFormat:@"http://maps.google.com/maps?daddr=%@@%f,%f&saddr=%@@%f,%f",[finalLocation stringByReplacingOccurrencesOfString:@" " withString:@"+"],tempLatitude,tempLongitude,[startLocation stringByReplacingOccurrencesOfString:@" " withString:@"+"],userCurrentLocation.coordinate.latitude,userCurrentLocation.coordinate.longitude];
		urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
		[[UIApplication sharedApplication] openURL: [NSURL URLWithString: urlString]];
	}
	
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
	
	self.userCurrentLocation = newLocation;
}

@end
